package com.turing.post.salesmanage.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.salesmanage.util.DepositOrder;
import com.turing.post.salesmanage.util.DepositOrderDao;
import com.turing.post.salesmanage.util.DepositOrderDetail;
import com.turing.post.salesmanage.util.DepositOrderDetailBusiness;
import com.turing.post.salesmanage.util.DepositOrderDetailDao;
import com.turing.post.salesmanage.util.SalesManageApplicationException;
import com.turing.post.salesmanage.util.SalesManageRespCode;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * 充值单卡充值明细（DepositOrderDetail）
 * 
 * @author zxp
 * @Jan 17, 2013
 */

@Stateless(mappedName = "salesmanage.impl.DepositOrderDetailBusinessImpl")
@Remote
@Local
public class DepositOrderDetailBusinessImpl implements
		DepositOrderDetailBusiness {

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;
	@EJB(mappedName = "salesmanage.impl.DepositOrderDetailDaoImpl")
	private DepositOrderDetailDao depositOrderDetailDaoImpl;

	@EJB(mappedName = "salesmanage.impl.DepositOrderDaoImpl")
	private DepositOrderDao depositOrderDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	private void errException(String error) throws PCPSApplicationException {
		throw new SalesManageApplicationException(
				SalesManageApplicationException.ERRCODE_CATEGORY_APPLICATION,
				SalesManageRespCode.DEPOSIT_EXCEPTIONCODE, error);
	}

	// 添加充值单卡充值明细
	@Override
	public void insertDepositOrderDetailInfo(PCPSWebInput webInput,
			BigInteger depositOrderId, List<DepositOrderDetail> depOrdDetailList)
			throws PCPSApplicationException {
		if (webInput.getOperId() == null
				|| PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			errException("操作员编号或归属机构号为空!");
		}
		// 查询充值单
		DepositOrder dor = depositOrderDaoImpl
				.getDepositOrderForUpdate(depositOrderId);
		if (dor == null) {
			errException("充值单编号错误未查询到充值单!");
		}
		// 判断状态
		if (!dor.getOrderStatus().equals(
				DepositOrder.DEPORDER_ORDERSTATUS_INPUT)) {
			errException("充值单状态为录入状态才可批量导入!");
		}
		if (depOrdDetailList == null || depOrdDetailList.size() < 1) {
			errException("导入批量充值卡信息为空!");
		}
		// 是否重复添加
		List<DepositOrderDetail> dodList = depositOrderDetailDaoImpl
				.getDepositOrderDetailListByDepositOrderId(dor
						.getDepositOrderId());
		if (dodList.size() > 0) {
			errException("该充值单已导入充值卡明细!");
		}
		// 检查所有充值单数据是否合法
		DepositOrderDetail dod = null;
		BigInteger sumAmount = BigInteger.ZERO;
		// PersonalCustom pc = null;
		// String nullPerCus = "";
		HashMap<Integer, String> batchNoMap = new HashMap<Integer, String>();
		for (int i = 0; i < depOrdDetailList.size(); i++) {
			dod = depOrdDetailList.get(i);
			if (PCPSUtil.isEmpty(dod.getCardSeqNo())
					|| PCPSUtil.isEmpty(dod.getCardNo())) {
				errException("批量充值卡顺序号、卡号都必须填写：" + dod.getCardSeqNo()
						+ dod.getCardNo());
			}
			// // 判断持卡人是否为空
			// if (dod.getName() == null) {
			// errException("批量充值持卡人不可为空!");
			// } else {
			// pc = personalCustomDaoImpl.getPersonalCustomByName(webInput,
			// dod.getName());
			// if (pc == null) {
			// nullPerCus = nullPerCus + " " + dod.getName();
			// }
			// }
			if (dod.getDepositAmount().compareTo(BigInteger.ZERO) <= 0) {
				errException("批量充值金额必须大于0!");
			}
			batchNoMap.put(i, dod.getCardSeqNo().substring(0, 12));
			sumAmount = sumAmount.add(dod.getDepositAmount());
		}
		// 判断持卡人是否存在
		// if (!PCPSUtil.isEmpty(nullPerCus)) {
		// errException("系统中不存在持卡人：" + nullPerCus);
		// }
		// 判断是否为充值卡
		// CardClassic cc = null;
		// for (int i = 0; i < batchNoMap.size(); i++) {
		// cc = cardClassicDaoImpl.getCardClassicByBatchNo(batchNoMap.get(i));
		// if (cc == null) {
		// errException("卡批次号" + batchNoMap.get(i) + "不存在!");
		// } else {
		// if (cc.getAllowDeposit().equals(
		// CardClassic.CARDCLASSIC_ALLOWDEPOSIT_NORECHARGE)) {
		// errException(batchNoMap.get(i) + "批次卡不允许充值!");
		// }
		// }
		// }
		// 查询发卡商
		String issueCompanyNo = PCPSUtil.getIssueCompanyNo(webInput);
		IssueCompany ic = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(issueCompanyNo);

		ActivateCard ac = null;
		String nullActivateCard = "";
		String batchNoExist = "";
		HashMap<String, BigInteger> customMap = new HashMap<String, BigInteger>();
		// 检查所有充值单卡是否合法
		for (int i = 0; i < depOrdDetailList.size(); i++) {
			dod = depOrdDetailList.get(i);
			ac = activateCardDaoImpl.getActivateCardByCardNo(dod.getCardNo());
			if (ac == null) {
				nullActivateCard = nullActivateCard + " " + dod.getCardNo();
			} else {
				// 判断单卡余额
				if (ic.getEachCardBalanceLimit() != null
						&& ic.getEachCardBalanceLimit().compareTo(
								BigInteger.ZERO) > 0) {
					if ((ac.getBalance().add(dod.getDepositAmount()))
							.compareTo(ic.getEachCardBalanceLimit()) > 0) {
						errException("单卡余额上限为：" + ic.getEachCardBalanceLimit()
								+ " " + ac.getCardNo() + "充值后余额为"
								+ ac.getBalance().add(dod.getDepositAmount())
								+ "已超出上限!");
					}
				}
				if (ac.getOwnerId() == null
						|| ac.getOwnerId().compareTo(BigInteger.ZERO) <= 0) {
					errException("卡：" + ac.getCardNo() + "持卡人ID为空!");
				}
				// 不为空时put
				customMap.put(ac.getCardNo(), ac.getOwnerId());
				if (!dod.getCardSeqNo().equals(ac.getCardSeqNo())) {
					batchNoExist = batchNoExist + " " + dod.getCardSeqNo();
				}
			}
		}
		// 判断卡是否在激活卡表中
		if (!PCPSUtil.isEmpty(nullActivateCard)) {
			errException("充值卡号非法：" + nullActivateCard);
		}
		if (!PCPSUtil.isEmpty(batchNoExist)) {
			errException("充值卡号与卡顺序号批次号不对应：" + batchNoExist);
		}
		// 循环插入卡充值数据
		for (int i = 0; i < depOrdDetailList.size(); i++) {
			dod = depOrdDetailList.get(i);
			dod.setDepositOrderId(depositOrderId);
			dod.setBatchNo(dod.getCardSeqNo().substring(0, 12));
			dod.setCustomId(customMap.get(dod.getCardNo()));
			depositOrderDetailDaoImpl.insertDepositOrderDetail(dod);
		}
		// 修改充值单充值金额
		dor.setTotalDepositAmount(sumAmount);
		depositOrderDaoImpl.updateDepositOrder(dor);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Add, "添加充值单卡充值明细", "DepositOrderId:"
						+ dor.getDepositOrderId());
	}

	// 删除
	@Override
	public void deleteDepositOrderDetailInfo(PCPSWebInput webInput,
			BigInteger depositOrderId) throws PCPSApplicationException {
		// 查询充值单
		DepositOrder dor = depositOrderDaoImpl
				.getDepositOrderForUpdate(depositOrderId);
		if (dor == null) {
			errException("充值单编号错误未查询到充值单!");
		}
		// 判断状态
		if (!dor.getOrderStatus().equals(
				DepositOrder.DEPORDER_ORDERSTATUS_INPUT)) {
			errException("充值单状态为录入状态才可批量导入!");
		}
		if (webInput.getOperId() == null) {
			errException("操作员编号为空!");
		} else {
			// 判断是否为本人删除
			if (dor.getOperId().compareTo(webInput.getOperId()) != 0) {
				errException("只允许创建人删除充值单!");
			}
		}
		// 是否有数据
		List<DepositOrderDetail> dodList = depositOrderDetailDaoImpl
				.getDepositOrderDetailListByDepositOrderId(dor
						.getDepositOrderId());
		if (dodList.size() < 1) {
			errException("无充值单卡明细数据可删除!");
		}
		// 如果已经有充值卡明细列表，先删除
		if (dodList.size() > 0) {
			Integer deleteCount = depositOrderDetailDaoImpl
					.deleteDepositOrderDetailByDepositOrderId(depositOrderId);
			if (deleteCount.intValue() < 0) {
				errException("删除充值单卡充值明细数据失败!");
			}
		}
		// 修改充值单充值金额
		dor.setTotalDepositAmount(BigInteger.ZERO);
		depositOrderDaoImpl.updateDepositOrder(dor);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Delete, "删除充值单卡充值明细", "DepositOrderId:"
						+ dor.getDepositOrderId());
	}
}